package purchasePlan

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"insighttracking/apps/admin/auth"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"
	"strings"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetPurchasePlanPageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetPurchasePlanPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetPurchasePlanPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetPurchasePlanPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetPurchasePlanPageApiLogic) GetPurchasePlanPageApi(req *types.GetPurchasePlanPageReq) (resp *types.PurchasePlanPageResp, err error) {
	// todo: add your logic here and delete this line
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	// 获取当前采购员和没有指定采购员的采购计划
	tx := dao.PurchasePlanEntity.WithContext(l.ctx).
		Where(dao.PurchasePlanEntity.EnterpriseID.Eq(accountInfo.EnterpriseId))
	if req.Types != "" {
		tx = tx.Where(dao.PurchasePlanEntity.Types.Eq(cast.ToInt64(req.Types)))
	}
	if req.SupplierID != "" {
		tx = tx.Where(dao.PurchasePlanEntity.DefaultSupplierID.Eq(cast.ToInt64(req.SupplierID)))
	}
	if req.PurchaserID != "" {
		tx = tx.Where(dao.PurchasePlanEntity.PurchaserID.Eq(cast.ToInt64(req.PurchaserID)))
	}
	if req.Name != "" {
		req.Name = strings.ReplaceAll(req.Name, "%", "\\%")
		req.Name = strings.ReplaceAll(req.Name, "_", "\\%")
		tx = tx.Where(dao.PurchasePlanEntity.SnapshotSpuName.Like("%" + req.Name + "%"))
	}
	if req.CategoryId != "" {
		tx = tx.Where()
	}
	if req.StartTime != "" && req.EndTime != "" {
		tx = tx.Where(dao.PurchasePlanEntity.CreatedAt.Between(utils.DateTimeStrToTime(req.StartTime), utils.DateTimeStrToTime(req.EndTime)))
	}
	offset, limit := utils.DbPage(req.PageNumber, req.PageSize)
	planEntities, count, err := tx.Order(dao.PurchasePlanEntity.ID.Desc()).FindByPage(offset, limit)
	if err != nil || len(planEntities) == 0 {
		return &types.PurchasePlanPageResp{
			Data: make([]types.PurchasePlanModel, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}
	var defaultSupplierIdList = make([]int64, 0)
	var purchaserIdList = make([]int64, 0)
	for _, item := range planEntities {
		defaultSupplierIdList = append(defaultSupplierIdList, item.DefaultSupplierID)
		defaultSupplierIdList = append(defaultSupplierIdList, item.SupplierID)
		purchaserIdList = append(purchaserIdList, item.PurchaserID)
	}
	supplierEntities, err := dao.SupplierEntity.WithContext(l.ctx).Where(dao.SupplierEntity.ID.In(k.Distinct(defaultSupplierIdList)...)).Find()
	var supplierNameMap = make(map[int64]string)
	if err == nil && len(supplierEntities) > 0 {
		supplierNameMap = k.ToMap(supplierEntities, func(item *model.SupplierEntity) (int64, string) {
			return item.ID, item.Name
		})
	}
	// 查询采购员
	personEntities, err := service.EnterprisePersonService.GetByIdListApi(l.ctx, accountInfo.EnterpriseId, k.Distinct(purchaserIdList))
	var personName = make(map[int64]string)
	if err == nil && len(personEntities) > 0 {
		personName = k.ToMap(personEntities, func(item *model.EnterprisePersonEntity) (int64, string) {
			return item.ID, item.Name
		})
	}
	var result = make([]types.PurchasePlanModel, 0)
	// 查询库存
	spuIdList := k.Map(planEntities, func(item *model.PurchasePlanEntity, index int) int64 {
		return item.SpuID
	})
	spuInventoryEntity := service.SpuInventoryService.SpuInventoryBySpuIdListAPi(l.ctx, k.Distinct(spuIdList), 0)

	for _, item := range planEntities {
		result = append(result, types.PurchasePlanModel{
			ID:                      item.ID,                                            // 主键id
			OrderNo:                 item.OrderNo,                                       // 操作流水号
			SupplierID:              item.SupplierID,                                    // 供应商,关联到supplier表主键id
			SupplierName:            supplierNameMap[item.SupplierID],                   // 供应商,关联到supplier表主键id
			DefaultSupplierID:       item.DefaultSupplierID,                             // 默认的供应商id
			DefaultSupplierName:     supplierNameMap[item.DefaultSupplierID],            // 默认供应商名称
			PurchaserID:             item.PurchaserID,                                   // 采购员,关联到
			PurchaserName:           personName[item.PurchaserID],                       // 采购员
			SpuID:                   item.SpuID,                                         // 商品,关联到spu表主键id
			SnapshotSpuName:         item.SnapshotSpuName,                               // 快照商品名称
			SnapshotProductImageURL: item.SnapshotProductImageURL,                       // 快照产品图片
			SnapshotSpuType:         item.SnapshotSpuType,                               // 快照商品类型,0表示基础商品,1表示加工商品
			SnapshotUnit:            item.SnapshotUnit,                                  // 快照单位
			SnapshotCategory:        item.SnapshotCategory,                              // 快照分类
			LossRate:                item.LossRate.StringFixed(2),                       // 快照损耗率
			ExpectationGoodsDate:    utils.TimestampToString(item.ExpectationGoodsDate), // 期望收货日期
			RequirementsCount:       item.RequirementsCount.StringFixed(2),              // 需求数量
			SnapshotPrice:           item.SnapshotPrice.StringFixed(2),                  // 快照采购单价
			PurchaserCount:          item.PurchaserCount.StringFixed(2),                 // 采购数量
			PurchaserAmount:         item.PurchaserAmount.StringFixed(2),                // 采购金额
			Source:                  item.Source,                                        // 来源,0表示pc端手动点击订单,1表示定时任务,2表示手机端创建,3pc端手动创建
			Status:                  item.Status,                                        // 状态,0表示待采购,1表示完成采购,2表示已经生成采购单,3表示取消采购
			CancelReason:            item.CancelReason,                                  // 取消采购原因
			Remark:                  item.Remark,                                        // 备注
			CreatedAt:               utils.TimestampToString(item.CreatedAt),            // 创建时间
			UpdatedAt:               utils.TimestampToString(item.UpdatedAt),            // 更新时间
			InventoryCount:          spuInventoryEntity[item.SpuID].StringFixed(2),      // 库存数量
		})
	}
	return &types.PurchasePlanPageResp{
		Data: result,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}
